package com.doubao.wechat.listener;

import com.doubao.common.result.Result;
import com.doubao.wechat.entity.PaymentOrder;
import com.doubao.wechat.mapper.PaymentOrderMapper;
import com.doubao.wechat.service.PaymentOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 支付回调处理器
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class PaymentCallbackHandler {

    private final PaymentOrderService paymentOrderService;
    private final ApplicationContext applicationContext;
    private final PaymentOrderMapper paymentOrderMapper; // 新增依赖

    /**
     * 获取会员订阅服务
     */
    private Object getMembershipSubscriptionService() {
        try {
            return applicationContext.getBean("membershipSubscriptionServiceImpl");
        } catch (Exception e) {
            log.warn("获取会员订阅服务失败", e);
            return null;
        }
    }

    /**
     * 处理支付成功回调
     *
     * @param orderId 订单ID
     * @param transactionId 微信支付交易号
     * @return 处理结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> handlePaymentSuccess(String orderId, String transactionId) {
        log.info("【支付回调】处理支付成功回调: orderId={}, transactionId={}", orderId, transactionId);

        try {
            // 查询订单信息
            Result<PaymentOrder> orderResult = paymentOrderService.getOrderByOutTradeNo(orderId);
            if (!orderResult.isSuccess() || orderResult.getData() == null) {
                log.error("【支付回调】获取订单信息失败: {}", orderResult.getMessage());
                return Result.failed("订单不存在");
            }

            PaymentOrder order = orderResult.getData();
            log.info("【支付回调】查询到订单信息: {}, 当前状态: {}", orderId, order.getStatus());

            // 检查订单是否已经处理
            if ("SUCCESS".equals(order.getStatus())) {
                log.info("【支付回调】订单已处理为成功状态，跳过: {}", orderId);
                return Result.success();
            }

            // 更新订单状态
            log.info("【支付回调】准备更新订单状态为SUCCESS: {}", orderId);
            Result<Void> updateResult = paymentOrderService.updateOrderStatus(
                    orderId, "SUCCESS", transactionId);
            if (!updateResult.isSuccess()) {
                log.error("【支付回调】更新订单状态失败: {}", updateResult.getMessage());
                return Result.failed("更新订单状态失败");
            }
            log.info("【支付回调】订单状态已更新为SUCCESS: {}", orderId);

            // 判断订单类型并处理
            String attach = order.getAttach();
            log.info("【支付回调】订单附加信息: {}", attach);
            
            if (attach != null && attach.startsWith("membershipOrder_")) {
                // 会员订阅订单
                log.info("【支付回调-会员订单】检测到会员订阅订单: {}, 金额: {} 分", orderId, order.getAmount());
                
                // 解析订单信息
                try {
                    String[] parts = attach.split("_");
                    if (parts.length >= 3) {
                        Long membershipId = Long.parseLong(parts[1]);
                        String subscriptionType = parts[2];
                        log.info("【支付回调-会员订单】会员订阅信息解析成功: membershipId={}, subscriptionType={}, userId={}", 
                                membershipId, subscriptionType, order.getUserId());
                        
                        if (subscriptionType.contains("MONTHLY")) {
                            log.info("【支付回调-会员订单】月卡会员订单支付成功: userId={}, membershipId={}, 金额={} 分", 
                                    order.getUserId(), membershipId, order.getAmount());
                        } else if (subscriptionType.contains("YEARLY")) {
                            log.info("【支付回调-会员订单】年卡会员订单支付成功: userId={}, membershipId={}, 金额={} 分", 
                                    order.getUserId(), membershipId, order.getAmount());
                        }
                    } else {
                        log.warn("【支付回调-会员订单】订单附加信息格式异常: {}, 拆分后长度为{}", attach, parts.length);
                    }
                } catch (Exception e) {
                    log.warn("【支付回调-会员订单】解析会员订阅信息失败: {}", e.getMessage());
                }
                
                // 调用会员订阅服务
                Object service = getMembershipSubscriptionService();
                if (service != null) {
                    try {
                        log.info("【支付回调-会员订单】开始调用会员订阅服务处理支付成功回调: {}", orderId);
                        
                        // 获取服务类名和方法名，用于日志
                        String serviceName = service.getClass().getSimpleName();
                        String methodName = "handleSubscriptionPaySuccess";
                        log.info("【支付回调-会员订单】调用服务: {}.{}({})", serviceName, methodName, orderId);
                        
                        Result<Void> result = (Result<Void>) service.getClass()
                                .getMethod(methodName, String.class)
                                .invoke(service, orderId);
                        
                        if (result.isSuccess()) {
                            log.info("【支付回调-会员订单】会员订阅服务处理成功: {}", orderId);
                        } else {
                            log.error("【支付回调-会员订单】会员订阅服务处理失败: {}, 错误: {}", orderId, result.getMessage());
                        }
                        
                        return result;
                    } catch (Exception e) {
                        log.error("【支付回调-会员订单】调用会员订阅服务异常", e);
                        return Result.failed("处理会员订阅失败: " + e.getMessage());
                    }
                } else {
                    log.error("【支付回调-会员订单】会员订阅服务不可用");
                    return Result.failed("会员订阅服务不可用");
                }
            } else {
                // 处理通用的支付成功回调逻辑
                log.info("【支付回调-普通订单】处理通用支付成功回调: {}", orderId);
                // 可以添加其他通用的处理逻辑，如发送通知等
                return Result.success();
            }
        } catch (Exception e) {
            log.error("【支付回调】处理支付成功回调异常", e);
            return Result.failed("处理支付回调异常: " + e.getMessage());
        }
    }

    /**
     * 处理支付失败回调
     *
     * @param orderId 订单ID
     * @param reason 失败原因
     * @return 处理结果
     */
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> handlePaymentFailed(String orderId, String reason) {
        log.info("处理支付失败回调: orderId={}, reason={}", orderId, reason);

        try {
            // 查询订单信息
            Result<PaymentOrder> orderResult = paymentOrderService.getOrderByOutTradeNo(orderId);
            if (!orderResult.isSuccess() || orderResult.getData() == null) {
                log.error("获取订单信息失败: {}", orderResult.getMessage());
                return Result.failed("订单不存在");
            }

            PaymentOrder order = orderResult.getData();

            // 检查订单是否已经处理
            if ("CLOSED".equals(order.getStatus()) || "FAILED".equals(order.getStatus())) {
                log.info("订单已处理，跳过: {}", orderId);
                return Result.success();
            }

            // 更新订单状态
            Result<Void> updateResult = paymentOrderService.updateOrderStatus(
                    orderId, "CLOSED", null);
            if (!updateResult.isSuccess()) {
                log.error("更新订单状态失败: {}", updateResult.getMessage());
                return Result.failed("更新订单状态失败");
            }

            // 判断订单类型并处理
            String attach = order.getAttach();
            if (attach != null && attach.startsWith("membershipOrder_")) {
                // 会员订阅订单
                Object service = getMembershipSubscriptionService();
                if (service != null) {
                    try {
                        return (Result<Void>) service.getClass()
                                .getMethod("handleSubscriptionPayFailed", String.class, String.class)
                                .invoke(service, orderId, reason);
                    } catch (Exception e) {
                        log.error("调用会员订阅服务失败", e);
                        return Result.failed("处理会员订阅失败: " + e.getMessage());
                    }
                } else {
                    log.error("会员订阅服务不可用");
                    return Result.failed("会员订阅服务不可用");
                }
            } else {
                // 处理通用的支付失败回调逻辑
                log.info("处理通用支付失败回调: {}, 原因: {}", orderId, reason);
                // 可以添加其他通用的处理逻辑，如发送通知等
                return Result.success();
            }
        } catch (Exception e) {
            log.error("处理支付失败回调异常", e);
            return Result.failed("处理支付回调异常: " + e.getMessage());
        }
    }
}